<script setup>
import { Modal } from 'ant-design-vue'
import { ColumnHeightOutlined, DownOutlined, DownloadOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, UpOutlined } from '@ant-design/icons-vue'
import { exportAccount, getAccountList, getAccountStatistics, resetFreeze, resetPass, resetUnfreeze } from '~@/api/user/index'

defineOptions({
  name: 'CONSUME',
})
const userStore = useUserStore()
const { hasPermission } = userStore
const statusMap = {
  0: '关闭',
  1: '运行中',
  2: '上线',
  3: '错误',
}
const message = useMessage()
const columns = shallowRef([
  {
    title: '持卡人姓名',
    dataIndex: 'userName',
    width: 150,
  },
  {
    title: '卡号',
    dataIndex: 'cardNo',
    width: 200,
  },
  {
    title: '持卡人手机号',
    dataIndex: 'phone',
    width: 150,
  },
  {
    title: '持卡人证件号',
    dataIndex: 'certNo',
    width: 200,
  },

  {
    title: '充值金额',
    dataIndex: 'rechargeFeeSum',
    width: 150,
  },
  {
    title: '消费金额',
    dataIndex: 'defrayFeeSum',
    width: 150,
  },
  {
    title: '退款金额',
    dataIndex: 'refundFeeSum',
    width: 150,
  },
  {
    title: '提现金额',
    dataIndex: 'withdrawalFeeSum',
    width: 150,
  },
  {
    title: '可用余额',
    dataIndex: 'balance',
    width: 150,
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    width: 100,

  },
  {
    title: '开卡时间',
    align: 'center',
    dataIndex: 'createTime',
    width: 200,
  },

  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 180,

  },
])
const tradeOptions = shallowRef([
  // { label: '支付', value: 'DEFRAY' },
  // { label: '退费', value: 'REFUND' },
  // { label: '充值', value: 'RECHARGE' },
  // { label: '提现', value: 'WITHDRAWAL' },
])

const accountOptions = shallowRef([
  { configKey: '', configValue: '全部' },
  { configKey: 'BALANCE', configValue: '余额账户' },
  { configKey: 'CREDIT', configValue: '信用账户' },
  { configKey: 'POINTS', configValue: '积分账户' },
  { configKey: 'MOBILE', configValue: '移动支付账户' },
])
const statusOptions = shallowRef([
  { configKey: 'ACTIVE', configValue: '正常' },
  { configKey: 'AUTO_FREEZE', configValue: '自动冻结' },
  { configKey: 'MANUAL_FREEZE', configValue: '人工冻结' },
  { configKey: 'CANCEL', configValue: '注销' },
])
const loading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  name: void 0,
  callNo: void 0,
  desc: void 0,
  status: void 0,
  updatedAt: void 0,
  accountType: void 0,
})
const staticInfo = reactive({
  cardCount: void 0,
  refundAmount: void 0,
  defrayAmount: void 0,
  balance: void 0,
  withdrawAmount: void 0,
  rechargeAmount: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  formModel.accountType = accountOptions.value[0].configKey
  init()
  getStatistics()
  // getType();
  // getChannel();
})
// 处理状态
function handleStatus(text) {
  switch (text) {
    case 'ACTIVE':
      return '正常'
    case 'AUTO_FREEZE':
      return '自动冻结'
    case 'MANUAL_FREEZE':
      return '人工冻结'
    default:
      return '注销'
  }
}

// 处理证件号
function handleCertcard(certNo) {
  if (!certNo)
    return ''
  const len = certNo.length
  if (len <= 4)
    return certNo // 短于4位不处理
  return certNo.slice(0, 3) + '*'.repeat(len - 7) + certNo.slice(-4)
}
// 查询卡信息
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const createBeginTime = formModel.cardDate?.[0]?.format('YYYY-MM-DD')
    const createEndTime = formModel.cardDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await getAccountList({
      param: { ...formModel, createBeginTime, createEndTime },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    // dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
// 查询卡统计信息
async function getStatistics() {
  try {
    const { data } = await getAccountStatistics(formModel)

    staticInfo.cardCount = data.cardCount
    staticInfo.rechargeAmount = data.rechargeAmount
    staticInfo.withdrawAmount = data.withdrawAmount
    staticInfo.defrayAmount = data.defrayAmount
    staticInfo.refundAmount = data.refundAmount
    staticInfo.balance = data.balance
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
async function onSearch() {
  pagination.current = 1
  await init()
  await getStatistics()
}
// 导出
async function exportExcel() {
  if (loading.value)
    return
  loading.value = true
  try {
    const createBeginTime = formModel.cardDate?.[0]?.format('YYYY-MM-DD')
    const createEndTime = formModel.cardDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await exportAccount({
      param: { ...formModel, createBeginTime, createEndTime },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })
    window.location.href = data.url
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
//
// 重置密码
async function handleReset(record) {
  Modal.confirm({
    title: '确认操作',
    centered: true,
    content: `确定要重置 ${record.userName} 的卡密码吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = resetPass({ cardNo: record.cardNo, userId: record.userId })
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              setTimeout(() => {
                resolve()
                init()
                message.success('重置成功')
              }, 500)
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}
// 冻结账户
async function handleFreeze(record) {
  Modal.confirm({
    title: '确认操作',
    centered: true,
    content: `确定要冻结卡号为 ${record.cardNo} 的账户吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = resetFreeze({ cardNo: record.cardNo })
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              setTimeout(() => {
                resolve()
                init()
                message.success('操作成功')
              }, 500)
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}

// 解冻账户
async function handleUnfreeze(record) {
  Modal.confirm({
    title: '确认操作',
    centered: true,
    content: `确定要解冻卡号为 ${record.cardNo} 的账户吗？`,
    okText: '确认',
    cancelText: '取消',
    onOk() {
      return new Promise((resolve, reject) => {
        const res = resetUnfreeze({ cardNo: record.cardNo })
          .then((res) => {
            if (res.data.code === 'SUCCESS') {
              setTimeout(() => {
                resolve()
                init()
                message.success('操作成功')
              }, 500)
              // setTimeout(resolve, 500)
            }
            else {
              message.error('操作失败')
              reject() // 保持对话框打开
            }
          })
          .catch(() => {
            // message.error('操作失败')
            reject() // 保持对话框打开
          })
      })
    },
    onCancel() {
      console.log('取消操作')
    },
  })
}
function handleReturn() {
  open.value = false
}
function handleOk() {
  open.value = false
  Modal.destroyAll()
  onSearch()
}
function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
function handleCheckAllChange(e) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}
const expand = ref(false)
</script>

<template>
  <page-container>
    <div v-if="open === false">
      <a-card mb-4>
        <a-form :label-col="{ span: 7 }" :model="formModel">
          <a-row :gutter="[15, 0]">
            <a-col :span="8">
              <a-form-item name="userName" label="持卡人姓名">
                <a-input v-model:value="formModel.userName" placeholder="模糊查询" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="cardNo" label="卡号">
                <a-input v-model:value="formModel.cardNo" placeholder="精确查询" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="phone" label="持卡人手机号">
                <a-input v-model:value="formModel.phone" placeholder="精确查询" allow-clear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="cardDate" label="开卡时间">
                <a-range-picker v-model:value="formModel.cardDate" allow-clear style="width:100%" />
              </a-form-item>
            </a-col>

            <a-col :span="8">
              <a-form-item name="accountType" label="账户类型">
                <a-select v-model:value="formModel.accountType" placeholder="请选择" allow-clear>
                  <a-select-option v-for="item in accountOptions" :key="item.configKey" :value="item.configKey">
                    {{ item.configValue }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="certNo" label="持卡人证件号">
                <a-input v-model:value="formModel.certNo" placeholder="精确查询" allow-clear />
              </a-form-item>
            </a-col>
          </a-row>
          <a-row v-if="expand" :gutter="[15, 0]">
            <a-col :span="8">
              <a-form-item name="status" label="状态">
                <a-select v-model:value="formModel.status" placeholder="请选择" allow-clear>
                  <a-select-option v-for="item in statusOptions" :key="item.configKey" :value="item.configKey">
                    {{ item.configValue }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row :span="24" style="text-align: right">
            <a-col :span="24">
              <a-space flex justify-end w-full>
                <!-- :loading="loading" -->
                <a-button type="primary" @click="onSearch">
                  <SearchOutlined />查询
                </a-button>
                <a-button v-if="hasPermission('card:info:export')" type="primary" class="ml-2" ghost @click="exportExcel()">
                  <DownloadOutlined />导出
                </a-button>
                <a-button type="link" @click="expand = !expand">
                  {{ expand ? '收起' : '高级筛选' }}
                  <UpOutlined v-if="expand" />
                  <DownOutlined v-else />
                </a-button>
              </a-space>
            </a-col>
          </a-row>
        </a-form>
      </a-card>

      <a-card>
        <a-row class="mb-5">
          <a-col :span="4">
            <a-statistic title="存济卡总张数 (张)" :value="staticInfo.cardCount" />
          </a-col>
          <a-col :span="4">
            <a-statistic title="充值总金额 (元)" :precision="2" :value="staticInfo.rechargeAmount" />
          </a-col>
          <a-col :span="4">
            <a-statistic title="消费总金额 (元)" :precision="2" :value="staticInfo.defrayAmount" />
          </a-col>
          <a-col :span="4">
            <a-statistic title="退款总金额 (元)" :precision="2" :value="staticInfo.refundAmount" />
          </a-col>
          <a-col :span="4">
            <a-statistic title="提现总金额 (元)" :precision="2" :value="staticInfo.withdrawAmount" />
          </a-col>
          <a-col :span="4">
            <a-statistic title="可用总金额 (元)" :precision="2" :value="staticInfo.balance" />
          </a-col>
        </a-row>
        <a-divider />
        <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'balance'">
              <span :style="{ color: record.balance < 0 ? 'red' : 'black' }">{{ Number(record.balance).toFixed(2) }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'rechargeFeeSum'">
              <span :style="{ color: record.rechargeFeeSum < 0 ? 'red' : 'black' }">{{ Number(record.rechargeFeeSum).toFixed(2) }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'defrayFeeSum'">
              <span :style="{ color: record.defrayFeeSum < 0 ? 'red' : 'black' }">{{ Number(record.defrayFeeSum).toFixed(2) }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'refundFeeSum'">
              <span :style="{ color: record.refundFeeSum < 0 ? 'red' : 'black' }">{{ Number(record.refundFeeSum).toFixed(2) }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'withdrawalFeeSum'">
              <span :style="{ color: record.withdrawalFeeSum < 0 ? 'red' : 'black' }">{{ Number(record.withdrawalFeeSum).toFixed(2) }}</span>
            </template>

            <template v-else-if="column.dataIndex === 'status'">
              <a-tag
                :color="record.status === 'ACTIVE' ? 'geekblue' : 'volcano'"
              >
                {{ handleStatus(record.status) }}
              </a-tag>
            </template>

            <template v-else-if="column.dataIndex === 'action'">
              <div class="action flex flex-center">
                <a @click="handleReset(record)">重置密码</a>
                <span class="middle-line">|</span>
                <a v-if="record.status === 'ACTIVE'" @click="handleFreeze(record)">冻结账户</a>
                <a v-if="record.status === 'MANUAL_FREEZE'" @click="handleUnfreeze(record)">解冻账户</a>
              </div>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
    <div v-else>
      <a-card class="transition-all-300" :bordered="false">
        <div class="flex flex-wrap justify-between">
          <span class="card-title">订单详情</span>
          <a-button class="mb-4" @click="handleReturn">
            <template #icon>
              <ArrowLeftOutlined />
            </template>
            返回
          </a-button>
        </div>

        <a-descriptions>
          <a-descriptions-item label="商户名称">
            {{ detailInfo.appName }}
          </a-descriptions-item>
          <a-descriptions-item label="平台订单号">
            {{ detailInfo.platRequestNo }}
          </a-descriptions-item>

          <a-descriptions-item label="商户订单号">
            {{ detailInfo.defrayNo ? detailInfo.defrayNo : "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="原平台订单号">
            {{ detailInfo.origPlatRequestNo ? detailInfo.origPlatRequestNo : "--" }}
          </a-descriptions-item>
          <a-descriptions-item label="交易卡号">
            {{ detailInfo.cardNo }}
          </a-descriptions-item>
          <a-descriptions-item label="交易类型">
            {{ handleTradeType(detailInfo.tradeType) }}
          </a-descriptions-item>
          <a-descriptions-item label="订单状态">
            {{ handleStatus(detailInfo.status) }}
          </a-descriptions-item>
        </a-descriptions>
        <a-divider style="margin-bottom: 32px" />
        <a-descriptions title="支付信息">
          <a-descriptions-item label="支付金额">
            {{ Number(detailInfo.defrayFee).toFixed(2) }}
          </a-descriptions-item>
          <a-descriptions-item label="充值提现渠道">
            {{ detailInfo.channelName ? detailInfo.channelName : '--' }}
          </a-descriptions-item>
          <a-descriptions-item label="支付开始时间">
            {{ detailInfo.requestStartTime }}
          </a-descriptions-item>
          <a-descriptions-item label="支付完成时间">
            {{ detailInfo.requestCompleteTime }}
          </a-descriptions-item>
        </a-descriptions>
        <a-divider style="margin-bottom: 32px" />
        <a-descriptions title="客户信息">
          <a-descriptions-item label="客户姓名">
            {{ detailInfo.userName }}
          </a-descriptions-item>
          <a-descriptions-item label="账号">
            {{ detailInfo.accountNo }}
          </a-descriptions-item>
          <a-descriptions-item label="联系电话">
            {{ detailInfo.phone }}
          </a-descriptions-item>
        </a-descriptions>
      </a-card>
      <div v-if="loading" class="fullscreen-loading">
        <a-spin size="large" />
      </div>
    </div>
  </page-container>
</template>

  <style lang="less" scoped>
.red{
      color:red;
      /* color:#ff4d4f; */
    }
    .card-title{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex: auto;
      color: rgba(0, 0, 0, 0.88);
      font-weight: 600;
      font-size: 16px;
      line-height: 1.5;
    }
  @media screen and (max-width: 1200px) and (min-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      margin-left: -44px;
      .statItem {
        padding: 0 16px;
      }
    }
  }

  @media screen and (max-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      float: none;
      margin-right: 0;
      .statItem {
        padding: 0 16px;
        text-align: left;
        &::after {
          display: none;
        }
      }
    }
  }

  @media screen and (max-width: 768px) {
    .extraContent {
      margin-left: -16px;
    }
    .projectList {
      .projectGrid {
        width: 50%;
      }
    }
  }

  @media screen and (max-width: 576px) {
    .pageHeaderContent {
      display: block;
      .content {
        margin-left: 0;
      }
    }
    .extraContent {
      .statItem {
        float: none;
      }
    }
  }

  @media screen and (max-width: 480px) {
    .projectList {
      .projectGrid {
        width: 100%;
      }
    }
  }
  </style>
